package org.exercise.schedule;

import lombok.Data;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @author Stranger
 * @version 1.0
 * @description: TODO
 * @date 2022/10/6 22:43
 */
@Data
public class ScheduleManager implements Schedule {

    private Timer timer;

    private Timer stopTimer;
    private int taskCount = 0;

    private final Object lock = new Object();

    public ScheduleManager(String name) {
        timer = new Timer(name);
    }

    @Override
    public void schedule(TimerTask task, long delay) {
        this.taskCount++;
        this.timer.schedule(task, delay);
    }

    @Override
    public void scheduleAtFixedRate(TimerTask task, Date firstTime, long period) {
        this.taskCount++;
        this.timer.scheduleAtFixedRate(task, firstTime, period);
    }

    @Override
    public void stop() {
        this.scheduleAtFixedRate((new ScheduleTask(() -> {

            synchronized (lock) {
                int purgeCount = this.timer.purge();
                this.taskCount -= purgeCount;
                if (this.taskCount == 0) {
                    this.timer.cancel();
                }
            }

        }, "")), new Date(), 500);
    }
}
